package configs

import (
	"fmt"
	"gopkg.in/ini.v1"
	"os"
)

var DatabaseConfig *database

type database struct {
	Host              string
	Port              int
	DbName            string
	Username          string
	Password          string
	Prefix            string
	MaxIdleConnNumber int
	MaxOpenConnNumber int
}

// LoadDatabaseConfig 加载数据库配置
func LoadDatabaseConfig() {
	if AppConfig == nil {
		fmt.Println("Fail to AppConfig not load!")
		os.Exit(1)
	}

	cfg, err := ini.Load(AppConfig.ConfPath + "/database.ini")
	if err != nil {
		fmt.Printf("Fail to read file database.ini: %v", err)
		os.Exit(1)
	}

	host := cfg.Section("database").Key("host").String()
	port, _ := cfg.Section("database").Key("port").Int()
	dbName := cfg.Section("database").Key("db_name").String()
	username := cfg.Section("database").Key("username").String()
	password := cfg.Section("database").Key("password").String()
	prefix := cfg.Section("database").Key("prefix").String()
	maxIdleConnNumber, _ := cfg.Section("database").Key("max_idle_conn_number").Int()
	maxOpenConnNumber, _ := cfg.Section("database").Key("max_open_conn_number").Int()

	DatabaseConfig = &database{
		Host:              host,
		Port:              port,
		DbName:            dbName,
		Username:          username,
		Password:          password,
		Prefix:            prefix,
		MaxIdleConnNumber: maxIdleConnNumber,
		MaxOpenConnNumber: maxOpenConnNumber,
	}
}
